package model

import "time"

// CardType 会员卡类型枚举
type CardType string

const (
	CardTypeAnnual      CardType = "ANNUAL"       // 年卡
	CardTypeMonthly     CardType = "MONTHLY"      // 月卡
	CardTypeTimes       CardType = "TIMES"        // 次卡
	CardTypeStoredValue CardType = "STORED_VALUE" // 储值卡
)

// CardStatus 会员卡状态枚举
type CardStatus string

const (
	CardStatusActive    CardStatus = "ACTIVE"    // 激活
	CardStatusExpired   CardStatus = "EXPIRED"   // 过期
	CardStatusFrozen    CardStatus = "FROZEN"    // 冻结
	CardStatusCancelled CardStatus = "CANCELLED" // 注销
)

// PaymentMethod 支付方式枚举
type PaymentMethod string

const (
	PaymentMethodCash     PaymentMethod = "CASH"      // 现金
	PaymentMethodAlipay   PaymentMethod = "ALIPAY"    // 支付宝
	PaymentMethodWechat   PaymentMethod = "WECHAT"    // 微信
	PaymentMethodBankCard PaymentMethod = "BANK_CARD" // 银行卡
	PaymentMethodOther    PaymentMethod = "OTHER"     // 其他
)

// PaymentStatus 支付状态枚举
type PaymentStatus string

const (
	PaymentStatusPending  PaymentStatus = "PENDING"  // 待支付
	PaymentStatusSuccess  PaymentStatus = "SUCCESS"  // 支付成功
	PaymentStatusFailed   PaymentStatus = "FAILED"   // 支付失败
	PaymentStatusRefunded PaymentStatus = "REFUNDED" // 已退款
)

// ConsumeType 消费类型枚举
type ConsumeType string

const (
	ConsumeTypeCourse  ConsumeType = "COURSE"  // 课程
	ConsumeTypeProduct ConsumeType = "PRODUCT" // 商品
	ConsumeTypeService ConsumeType = "SERVICE" // 服务
	ConsumeTypeOther   ConsumeType = "OTHER"   // 其他
)

// ChangeType 余额变动类型枚举
type ChangeType string

const (
	ChangeTypeRecharge ChangeType = "RECHARGE" // 充值
	ChangeTypeConsume  ChangeType = "CONSUME"  // 消费
	ChangeTypeRefund   ChangeType = "REFUND"   // 退款
	ChangeTypeAdjust   ChangeType = "ADJUST"   // 调整
	ChangeTypeBonus    ChangeType = "BONUS"    // 赠送
)

// ==================== 数据库模型 ====================

// MembershipCardType 会员卡类型表
type MembershipCardType struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	Name          string    `gorm:"size:50;not null" json:"name" binding:"required"`
	Type          CardType  `gorm:"type:varchar(20);not null;index" json:"type" binding:"required"`
	Price         float64   `gorm:"type:decimal(10,2);not null" json:"price" binding:"required,gt=0"`
	OriginalPrice float64   `gorm:"type:decimal(10,2)" json:"originalPrice"`
	ValidityDays  int       `gorm:"comment:有效天数" json:"validityDays"`
	TotalTimes    int       `gorm:"comment:总次数" json:"totalTimes"`
	Description   string    `gorm:"type:text" json:"description"`
	Benefits      string    `gorm:"type:json;comment:权益说明" json:"benefits"`
	IsActive      bool      `gorm:"default:true;index" json:"isActive"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

func (MembershipCardType) TableName() string {
	return "card_types"
}

// MembershipCard 会员卡表
type MembershipCard struct {
	ID             uint       `gorm:"primaryKey" json:"id"`
	CardNo         string     `gorm:"size:32;uniqueIndex;not null;comment:卡号" json:"cardNo"`
	MemberID       uint       `gorm:"not null;index;comment:会员ID" json:"memberId" binding:"required"`
	CardTypeID     uint       `gorm:"not null;comment:卡类型ID" json:"cardTypeId" binding:"required"`
	Status         CardStatus `gorm:"type:varchar(20);default:ACTIVE;index;comment:卡状态" json:"status"`
	Balance        float64    `gorm:"type:decimal(10,2);default:0.00;comment:余额" json:"balance"`
	RemainingTimes int        `gorm:"comment:剩余次数" json:"remainingTimes"`
	StartDate      time.Time  `gorm:"type:date;not null;comment:生效日期" json:"startDate" binding:"required"`
	ExpireDate     *time.Time `gorm:"type:date;index;comment:到期日期" json:"expireDate"`
	ActivatedAt    *time.Time `gorm:"comment:激活时间" json:"activatedAt"`
	FrozenAt       *time.Time `gorm:"comment:冻结时间" json:"frozenAt"`
	FrozenReason   string     `gorm:"size:200;comment:冻结原因" json:"frozenReason"`
	CancelledAt    *time.Time `gorm:"comment:注销时间" json:"cancelledAt"`
	CancelReason   string     `gorm:"size:200;comment:注销原因" json:"cancelReason"`
	CreatedAt      time.Time  `json:"createdAt"`
	UpdatedAt      time.Time  `json:"updatedAt"`

	// 关联关系
	Member   *Member             `gorm:"foreignKey:MemberID" json:"member,omitempty"`
	CardType *MembershipCardType `gorm:"foreignKey:CardTypeID" json:"cardType,omitempty"`
}

func (MembershipCard) TableName() string {
	return "membership_cards"
}

// RechargeRecord 充值记录表
type RechargeRecord struct {
	ID            uint          `gorm:"primaryKey" json:"id"`
	OrderNo       string        `gorm:"size:64;uniqueIndex;not null;comment:订单号" json:"orderNo"`
	CardID        uint          `gorm:"not null;index;comment:会员卡ID" json:"cardId" binding:"required"`
	MemberID      uint          `gorm:"not null;index;comment:会员ID" json:"memberId" binding:"required"`
	Amount        float64       `gorm:"type:decimal(10,2);not null;comment:充值金额" json:"amount" binding:"required,gt=0"`
	BonusAmount   float64       `gorm:"type:decimal(10,2);default:0.00;comment:赠送金额" json:"bonusAmount"`
	ActualAmount  float64       `gorm:"type:decimal(10,2);not null;comment:实际到账金额" json:"actualAmount"`
	PaymentMethod PaymentMethod `gorm:"type:varchar(20);not null;comment:支付方式" json:"paymentMethod" binding:"required"`
	PaymentStatus PaymentStatus `gorm:"type:varchar(20);default:PENDING;index;comment:支付状态" json:"paymentStatus"`
	TransactionNo string        `gorm:"size:100;comment:第三方交易号" json:"transactionNo"`
	OperatorID    *uint         `gorm:"comment:操作员ID" json:"operatorId"`
	Remark        string        `gorm:"size:500;comment:备注" json:"remark"`
	PaidAt        *time.Time    `gorm:"comment:支付时间" json:"paidAt"`
	CreatedAt     time.Time     `gorm:"index" json:"createdAt"`
	UpdatedAt     time.Time     `json:"updatedAt"`

	// 关联关系
	Card     *MembershipCard `gorm:"foreignKey:CardID" json:"card,omitempty"`
	Member   *Member         `gorm:"foreignKey:MemberID" json:"member,omitempty"`
	Operator *User           `gorm:"foreignKey:OperatorID" json:"operator,omitempty"`
}

func (RechargeRecord) TableName() string {
	return "recharge_records"
}

// ConsumptionRecord 消费记录表
type ConsumptionRecord struct {
	ID            uint        `gorm:"primaryKey" json:"id"`
	RecordNo      string      `gorm:"size:64;uniqueIndex;not null;comment:消费单号" json:"recordNo"`
	CardID        uint        `gorm:"not null;index;comment:会员卡ID" json:"cardId" binding:"required"`
	MemberID      uint        `gorm:"not null;index;comment:会员ID" json:"memberId" binding:"required"`
	ConsumeType   ConsumeType `gorm:"type:varchar(20);not null;index;comment:消费类型" json:"consumeType" binding:"required"`
	RelatedID     *uint       `gorm:"comment:关联ID" json:"relatedId"`
	Amount        float64     `gorm:"type:decimal(10,2);not null;comment:消费金额" json:"amount"`
	Times         int         `gorm:"default:0;comment:消费次数" json:"times"`
	BeforeBalance float64     `gorm:"type:decimal(10,2);comment:消费前余额" json:"beforeBalance"`
	AfterBalance  float64     `gorm:"type:decimal(10,2);comment:消费后余额" json:"afterBalance"`
	BeforeTimes   int         `gorm:"comment:消费前次数" json:"beforeTimes"`
	AfterTimes    int         `gorm:"comment:消费后次数" json:"afterTimes"`
	OperatorID    *uint       `gorm:"comment:操作员ID" json:"operatorId"`
	Remark        string      `gorm:"size:500;comment:备注" json:"remark"`
	CreatedAt     time.Time   `gorm:"index" json:"createdAt"`

	// 关联关系
	Card     *MembershipCard `gorm:"foreignKey:CardID" json:"card,omitempty"`
	Member   *Member         `gorm:"foreignKey:MemberID" json:"member,omitempty"`
	Operator *User           `gorm:"foreignKey:OperatorID" json:"operator,omitempty"`
}

func (ConsumptionRecord) TableName() string {
	return "consumption_records"
}

// BalanceLog 余额变动日志表
type BalanceLog struct {
	ID            uint       `gorm:"primaryKey" json:"id"`
	CardID        uint       `gorm:"not null;index;comment:会员卡ID" json:"cardId"`
	MemberID      uint       `gorm:"not null;index;comment:会员ID" json:"memberId"`
	ChangeType    ChangeType `gorm:"type:varchar(20);not null;index;comment:变动类型" json:"changeType"`
	Amount        float64    `gorm:"type:decimal(10,2);not null;comment:变动金额" json:"amount"`
	BeforeBalance float64    `gorm:"type:decimal(10,2);not null;comment:变动前余额" json:"beforeBalance"`
	AfterBalance  float64    `gorm:"type:decimal(10,2);not null;comment:变动后余额" json:"afterBalance"`
	RelatedNo     string     `gorm:"size:64;comment:关联单号" json:"relatedNo"`
	OperatorID    *uint      `gorm:"comment:操作员ID" json:"operatorId"`
	Remark        string     `gorm:"size:500;comment:备注" json:"remark"`
	CreatedAt     time.Time  `gorm:"index" json:"createdAt"`

	// 关联关系
	Card     *MembershipCard `gorm:"foreignKey:CardID" json:"card,omitempty"`
	Member   *Member         `gorm:"foreignKey:MemberID" json:"member,omitempty"`
	Operator *User           `gorm:"foreignKey:OperatorID" json:"operator,omitempty"`
}

func (BalanceLog) TableName() string {
	return "balance_logs"
}

// ==================== 请求响应模型 ====================

// CardTypeCreateReq 创建卡类型请求
type CardTypeCreateReq struct {
	Name          string   `json:"name" binding:"required"`
	Type          CardType `json:"type" binding:"required,oneof=ANNUAL MONTHLY TIMES STORED_VALUE"`
	Price         float64  `json:"price" binding:"required,gt=0"`
	OriginalPrice float64  `json:"originalPrice"`
	ValidityDays  int      `json:"validityDays"`
	TotalTimes    int      `json:"totalTimes"`
	Description   string   `json:"description"`
	Benefits      []string `json:"benefits"`
}

// CardTypeUpdateReq 更新卡类型请求
type CardTypeUpdateReq struct {
	Name          string   `json:"name"`
	Price         float64  `json:"price" binding:"omitempty,gt=0"`
	OriginalPrice float64  `json:"originalPrice"`
	ValidityDays  int      `json:"validityDays"`
	TotalTimes    int      `json:"totalTimes"`
	Description   string   `json:"description"`
	Benefits      []string `json:"benefits"`
	IsActive      *bool    `json:"isActive"`
}

// CardCreateReq 开卡请求
type CardCreateReq struct {
	MemberID      uint          `json:"memberId" binding:"required"`
	CardTypeID    uint          `json:"cardTypeId" binding:"required"`
	PaymentMethod PaymentMethod `json:"paymentMethod" binding:"required,oneof=CASH ALIPAY WECHAT BANK_CARD OTHER"`
	PaymentAmount float64       `json:"paymentAmount" binding:"required,gt=0"`
	StartDate     string        `json:"startDate" binding:"required"`
	Remark        string        `json:"remark"`
}

// CardRenewReq 续卡请求
type CardRenewReq struct {
	ExtendDays    int           `json:"extendDays" binding:"required,gt=0"`
	PaymentMethod PaymentMethod `json:"paymentMethod" binding:"required,oneof=CASH ALIPAY WECHAT BANK_CARD OTHER"`
	PaymentAmount float64       `json:"paymentAmount" binding:"required,gt=0"`
	Remark        string        `json:"remark"`
}

// CardFreezeReq 冻结/解冻卡请求
type CardFreezeReq struct {
	Action string `json:"action" binding:"required,oneof=FREEZE UNFREEZE"`
	Reason string `json:"reason"`
}

// CardCancelReq 注销卡请求
type CardCancelReq struct {
	Reason       string  `json:"reason" binding:"required"`
	RefundAmount float64 `json:"refundAmount"`
}

// RechargeReq 充值请求
type RechargeReq struct {
	Amount        float64       `json:"amount" binding:"required,gt=0"`
	PaymentMethod PaymentMethod `json:"paymentMethod" binding:"required,oneof=CASH ALIPAY WECHAT BANK_CARD OTHER"`
	BonusAmount   float64       `json:"bonusAmount"`
	Remark        string        `json:"remark"`
}

// ConsumeReq 消费请求
type ConsumeReq struct {
	ConsumeType ConsumeType `json:"consumeType" binding:"required,oneof=COURSE PRODUCT SERVICE OTHER"`
	RelatedID   *uint       `json:"relatedId"`
	Amount      float64     `json:"amount" binding:"required,gt=0"`
	Times       int         `json:"times"`
	Remark      string      `json:"remark"`
}

// ==================== 响应模型 ====================

// CardResp 会员卡响应
type CardResp struct {
	ID             uint       `json:"id"`
	CardNo         string     `json:"cardNo"`
	MemberName     string     `json:"memberName"`
	CardTypeName   string     `json:"cardTypeName"`
	Status         CardStatus `json:"status"`
	Balance        float64    `json:"balance"`
	RemainingTimes *int       `json:"remainingTimes"`
	ExpireDate     *string    `json:"expireDate"`
	DaysRemaining  int        `json:"daysRemaining"`
}

// CardDetailResp 会员卡详情响应
type CardDetailResp struct {
	*MembershipCard
	RecentRecharges    []RechargeRecord    `json:"recentRecharges"`
	RecentConsumptions []ConsumptionRecord `json:"recentConsumptions"`
}

// RechargeResp 充值响应
type RechargeResp struct {
	OrderNo      string    `json:"orderNo"`
	Amount       float64   `json:"amount"`
	BonusAmount  float64   `json:"bonusAmount"`
	ActualAmount float64   `json:"actualAmount"`
	BalanceAfter float64   `json:"balanceAfter"`
	PaidAt       time.Time `json:"paidAt"`
}

// ConsumeResp 消费响应
type ConsumeResp struct {
	RecordNo      string  `json:"recordNo"`
	Amount        float64 `json:"amount"`
	Times         int     `json:"times"`
	BeforeBalance float64 `json:"beforeBalance"`
	AfterBalance  float64 `json:"afterBalance"`
	BeforeTimes   *int    `json:"beforeTimes"`
	AfterTimes    *int    `json:"afterTimes"`
}

// BalanceResp 余额响应
type BalanceResp struct {
	Balance        float64 `json:"balance"`
	RemainingTimes *int    `json:"remainingTimes"`
	ExpireDate     *string `json:"expireDate"`
	DaysRemaining  int     `json:"daysRemaining"`
	Status         string  `json:"status"`
}

// StatisticsResp 统计响应
type StatisticsResp struct {
	TotalRecharge float64            `json:"totalRecharge"`
	TotalConsume  float64            `json:"totalConsume"`
	ConsumeByType map[string]float64 `json:"consumeByType"`
	ConsumeCount  int64              `json:"consumeCount"`
	AvgConsume    float64            `json:"avgConsume"`
}

// TransactionResp 交易记录响应
type TransactionResp struct {
	ID          uint      `json:"id"`
	Type        string    `json:"type"`
	TypeText    string    `json:"typeText"`
	Amount      float64   `json:"amount"`
	Balance     float64   `json:"balance"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"createdAt"`
	RelatedNo   string    `json:"relatedNo"`
}
